import json
import os
import re

from django.db import connection
from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import render, redirect

from django.views import View

from Oa_system.models import Staffing
from administrative.models import Topicsattachments, Topics, OfficialDocuments, ConferenceMemo, PersonalAttachments
from personal_center.models import User, SealApply


def type_to_char(type):
    if type == 'gw':
        return '公文'
    elif type == 'lw':
        return '上级来文'
    elif type == 'yt':
        return '议题'
    elif type == 'yysq':
        return '用印申请'
    elif type == 'zdy':
        return '自定义'
    elif type == 'yx':
        return '邮箱'
    else:
        return '无'


class DocumentCenterView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        yz_obj = Staffing.objects.get(station='院长')
        sj_obj = Staffing.objects.get(station='书记')
        if request.user.id in [yz_obj.user.id, sj_obj.user.id, 2]:
            sql = '''
            SELECT source, 
            case when source = 'gw' then '公文'
            when source = 'lw' then '上级来文'
            when source = 'yt' then '议题'
            when source = 'yysq' then '用印申请'
            when source = 'zdy' then '自定义' 
            when source = 'yx' then '邮箱'
            else '无' end as source_describe,
            SUM(num) as num
            FROM (SELECT
            source,
            count(source) as num
            FROM administrative_topicsattachments a 
             WHERE source in ('gw','lw','yt','yysq','zdy', 'yx')  and b.user_id = %s
            GROUP BY source 
            union all
            
            SELECT
            'gw' as source,
            0 as num
            union all
            
            SELECT
            'lw' as source,
            0 as num
            union all
            
            SELECT
            'yt' as source,
            0 as num
            union all
            
            SELECT
            'yysq' as source,
            0 as num
            union all
            
            SELECT
            'zdy' as source,
            0 as num) base GROUP BY source order by source
            
            '''
        else:
            sql = '''
                        SELECT source, 
                        case when source = 'gw' then '公文'
                        when source = 'lw' then '上级来文'
                        when source = 'yt' then '议题'
                        when source = 'yysq' then '用印申请'
                        when source = 'zdy' then '自定义' 
                        when source = 'yx' then '邮箱'
                        else '无' end as source_describe,
                        SUM(num) as num
                        FROM (SELECT
                        source,
                        count(source) as num
                        FROM administrative_topicsattachments a 
                        inner join administrative_topicsattachments_watch_users b on b.topicsattachments_id = a.id
                         WHERE source in ('gw','lw','yt','yysq','zdy', 'yx')  and b.user_id = %s
                        GROUP BY source 
                        union all

                        SELECT
                        'gw' as source,
                        0 as num
                        union all

                        SELECT
                        'lw' as source,
                        0 as num
                        union all

                        SELECT
                        'yt' as source,
                        0 as num
                        union all

                        SELECT
                        'yysq' as source,
                        0 as num
                        union all

                        SELECT
                        'zdy' as source,
                        0 as num) base GROUP BY source order by source

                        ''' % request.user.id
        one_dict = {}
        source_list = []
        with connection.cursor() as cursor:
            cursor.execute(sql)
            all_data = cursor.fetchall()
            for i in all_data:
                source_list.append({
                    'source': i[0],
                    'source_describe': i[1],
                    'num': i[2]
                })
        # print(one_dict)
        context = {'realname': real_name, 'position': position, 'department': department, 'source_list': source_list}
        return render(request, "document_management/document_center_view.html", context)

    def post(self, request):
        user = request.user
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        datavalue = request.POST.get('datavalue', 'gw')
        search_value = request.POST.get('search_value', None)
        # print("datavalue: ", datavalue)
        # print("search_value: ", search_value)
        # doc_url = "document-management/document_center_view"
        if search_value:
            attachments_objs = user.attachments_watch_users.filter(source=datavalue).filter(
                Q(uploader_user__real_name__contains=search_value) | Q(
                    uploader_user__company__name__contains=search_value)).order_by('-create_time')
        else:
            attachments_objs = user.attachments_watch_users.filter(source=datavalue).order_by('-create_time')
        record_list = [{"file_size": obj.file_size,
                        # "doc_name": os.path.splitext(os.path.basename(obj.file_path.name))[0],
                        "doc_name": os.path.splitext(obj.file_name)[0],
                        "doc_type": type_to_char(obj.source),
                        "source": obj.source,
                        "doc_depart": obj.uploader_user.company.name,
                        "user": obj.uploader_user.real_name,
                        "upload_time": obj.create_time.strftime("%Y-%m-%d %H:%M"),
                        "file_path": obj.pdf_path if obj.pdf_path else '/media/' + obj.file_path.name,
                        "id": obj.id
                        } for obj in attachments_objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'code': 200, "totals": attachments_objs.count(),
                      "data": record_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class PersonalAttachmentView(View):
    def get(self, request):
        real_name = request.user.real_name
        position = request.user.post
        department = request.user.company.name
        sql = '''
        SELECT is_secrecy , sum(num) as num FROM 
        (
        SELECT '公开' as is_secrecy, count(is_secrecy) as num  
        FROM `administrative_personalattachments` a
        where  is_secrecy = TRUE 
        GROUP BY is_secrecy
        union all
        SELECT '私密' as is_secrecy , count(id) as num FROM (
				SELECT  a.id as id  
        FROM `administrative_personalattachments` a
        left join administrative_personalattachments_watched_users b on a.id = b.personalattachments_id
        where  is_secrecy = FALSE and (uploader_user_id = %(user_id)s or b.user_id = %(user_id)s) GROUP BY a.id) b
        union all
        SELECT '公开' as is_secrecy, 0 as num
        union all
        SELECT '私密' as is_secrecy, 0 as num) base GROUP BY is_secrecy

        '''
        one_dict = {}
        with connection.cursor() as cursor:
            cursor.execute(sql, {'user_id': request.user.id})
            all_data = cursor.fetchall()
            for i in all_data:
                one_dict[i[0]] = i[1]
        context = {'realname': real_name, 'position': position, 'department': department, 'one_dict': one_dict}
        # 换成个人文件页面
        return render(request, "document_management/peresonal_document_view.html", context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        datavalue = request.POST.get('datavalue', 'true')
        search_value = request.POST.get('search_value', None)
        user = request.user
        # doc_url = "document-management/document_center_view"
        if datavalue == 'true':
            attachments_objs = PersonalAttachments.objects.filter(is_secrecy=True).order_by('-create_time')
        else:
            attachments_objs = (user.personalattachments_set.filter(is_secrecy=False).order_by(
                '-create_time') | user.personal_attachments_users.filter(is_secrecy=False).order_by(
                '-create_time')).distinct()
        record_list = [{"file_size": obj.file_size,
                        "doc_name": obj.file_name,
                        "doc_depart": obj.uploader_user.department,
                        "user": obj.uploader_user.real_name,
                        "upload_time": obj.create_time.strftime("%Y-%m-%d %H:%M"),
                        "file_path": obj.pdf_path if obj.pdf_path else '/media/' + obj.file_path.name,
                        "id": obj.id
                        } for obj in attachments_objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'code': 200, "totals": attachments_objs.count(),
                      "data": record_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class PersonalAttachmentWriteView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        is_secrecy = request.POST.get('is_secrecy', None)  # 'true' 'false'
        watched_users = request.POST.get('watched_users', None)  # 孔智慧(8166)
        obj = PersonalAttachments.objects.get(id=id)
        if is_secrecy == 'true':
            obj.is_secrecy = True
            obj.save()
        else:
            obj.is_secrecy = False
            if watched_users:
                watched_users = re.findall('\((.*?)\)', watched_users)
                watched_user_objs = User.objects.filter(job_number__in=watched_users)
                for watched_user_obj in watched_user_objs:
                    obj.watched_users.add(watched_user_obj)
            obj.save()
        returnData = {'code': 200, 'message': 'successful！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class CheckDocumentView(View):
    def post(self, request):
        source = request.POST.get("source", None)
        id = request.POST.get("id", None)
        obj = Topicsattachments.objects.get(id=int(id))
        if source == 'yt':
            topics_obj = Topics.objects.filter(uuid=obj.topics_number).first()
            if topics_obj:
                allow_list = [record.audit_people for record in topics_obj.topicsauditrecord_set.all()]
                allow_list.append(topics_obj.employee)
                if request.user in allow_list:
                    returnDict = {'code': 200, "message": "success",
                                  "file_path": obj.pdf_path if obj.pdf_path else '/media/' + obj.file_path.name, }
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                else:
                    returnDict = {'code': 400, "message": "该文件暂未公开！"}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")

            else:
                returnDict = {'code': 400, "message": "未找到主流程" }
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
        elif source == 'lw':
            official_obj = OfficialDocuments.objects.filter(uuid=obj.topics_number).first()
            if official_obj:
                allow_list = [record.audit_people for record in official_obj.officialdocumentsauditrecord_set.all()]
                accept_list = [record.audit_people for record in official_obj.officialdocumentspeople_set.all()]
                allow_list.append(official_obj.apply_user)
                allow_list = allow_list + accept_list
                if request.user in allow_list:
                    returnDict = {'code': 200, "message": "success",
                                  "file_path": obj.pdf_path if obj.pdf_path else '/media/' + obj.file_path.name, }
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                else:
                    returnDict = {'code': 400, "message": "该文件暂未公开！"}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")

            else:
                returnDict = {'code': 400, "message": "未找到主流程"}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
        elif source == 'gw':
            conference_obj = ConferenceMemo.objects.filter(number=obj.topics_number).first()
            if conference_obj:
                allow_list = [record.audit_people for record in conference_obj.conferencememoauditrecord_set.all()]
                accept_list = [record.audit_people for record in conference_obj.conferencememopeople_set.all()]
                allow_list.append(conference_obj.apply_user)
                allow_list = allow_list + accept_list
                if request.user in allow_list:
                    returnDict = {'code': 200, "message": "success",
                                  "file_path": obj.pdf_path if obj.pdf_path else '/media/' + obj.file_path.name, }
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                else:
                    returnDict = {'code': 400, "message": "该文件暂未公开！"}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")

            else:
                returnDict = {'code': 400, "message": "未找到主流程"}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            returnDict = {'code': 200, "message": "success",
                          "file_path": obj.pdf_path if obj.pdf_path else '/media/' + obj.file_path.name, }
            return HttpResponse(json.dumps(returnDict), content_type="application/json")


class DealDataView(View):
    def get(self, request):
        source = request.GET.get('source', None)
        if source == 'gw':
            fj_objs = Topicsattachments.objects.filter(source='gw')
            for fj_obj in fj_objs:
                gw_objs = ConferenceMemo.objects.filter(number=fj_obj.topics_number)
                for gw_obj in gw_objs:
                    for record in gw_obj.conferencememoauditrecord_set.all():
                        fj_obj.watch_users.add(record.audit_people)
                    for item in gw_obj.conferencememopeople_set.all():
                        fj_obj.watch_users.add(item.audit_people)
        elif source == 'yt':
            fj_objs = Topicsattachments.objects.filter(source='yt')
            for fj_obj in fj_objs:
                yt_objs = Topics.objects.filter(uuid=fj_obj.topics_number)
                for yt_obj in yt_objs:
                    fj_obj.watch_users.add(yt_obj.employee)
                    for record in yt_obj.topicsauditrecord_set.all():
                        fj_obj.watch_users.add(record.audit_people)
        elif source == 'lw':
            fj_objs = Topicsattachments.objects.filter(source='lw')
            for fj_obj in fj_objs:
                lw_objs = OfficialDocuments.objects.filter(uuid=fj_obj.topics_number)
                for lw_obj in lw_objs:
                    fj_obj.watch_users.add(lw_obj.apply_user)
                    for record in lw_obj.officialdocumentsauditrecord_set.all():
                        fj_obj.watch_users.add(record.audit_people)
                    for item in lw_obj.officialdocumentspeople_set.all():
                        fj_obj.watch_users.add(item.audit_people)
        elif source == 'yysq':
            fj_objs = Topicsattachments.objects.filter(source='yysq')
            for fj_obj in fj_objs:
                yysq_objs = SealApply.objects.filter(fj_number=fj_obj.topics_number)
                for yysq_obj in yysq_objs:
                    fj_obj.watch_users.add(yysq_obj.apply_user)
                    for record in yysq_obj.sealapplyauditrecord_set.all():
                        fj_obj.watch_users.add(record.audit_people)

        returnDict = {'code': 200, "message": "ok"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")